package com.fjec.devops.schedule.handler;

import com.fjec.common.jxls.DataSixUpload;
import com.fjec.common.schedule.BaseScheduleHandler;
import com.fjec.common.util.Base64Util;
import com.fjec.common.util.BizUtil;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.JsonUtil;
import com.fjec.devops.entity.BizYsOfflineRegResult;
import com.fjec.devops.feign.BaseClient;
import com.fjec.devops.feign.MarketClient;
import com.fjec.devops.service.IBizYsOfflineRegResultService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReader;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class YsOffLineRegResultHandler extends BaseScheduleHandler {

    @Resource
    private IBizYsOfflineRegResultService ysOfflineRegResultService;

    @Resource
    private BaseClient baseClient;

    @Resource
    private MarketClient marketClient;

    private XLSReader mainReader;

    public String handle(int limit, int numPerTimes) {
        List<Map<String, Object>> errorList = new ArrayList<>();
        List<BizYsOfflineRegResult> entityList = ysOfflineRegResultService.getUnhandledEntityList(limit);
        Map<String, Object> tmpMap;
        for (BizYsOfflineRegResult entity : entityList) {
            try {
                int success = 0;
                List<String> faultList = new ArrayList<>();
                // 获取Excel
                tmpMap = baseClient.getOSSFileBase64ById(entity.getFileId());
                String base64 = MapUtils.getString(tmpMap, "base64");
                byte[] excelBytes = Base64Util.decode2Bytes(base64);
//                FileUtils.writeByteArrayToFile(new File("D:\\" + entity.getFileName()), excelBytes);
                // 分析Excel
                DataSixUpload data = new DataSixUpload();
                List<DataSixUpload> dataList = new ArrayList<>();
                tmpMap = new HashMap<>();
                tmpMap.put("data", data);
                tmpMap.put("dataList", dataList);
                mainReader.read(new ByteArrayInputStream(excelBytes), tmpMap);
                // 计算处理次数
                int times = BizUtil.computeHandleTimes(dataList.size(), numPerTimes);
                // 处理数据
                for (int i = 0; i < times; i++) {
                    int fromIndex = i * numPerTimes;
                    int toIndex = i * numPerTimes + numPerTimes;
                    if (toIndex > dataList.size()) {
                        toIndex = dataList.size();
                    }
                    List<DataSixUpload> subDataList = dataList.subList(fromIndex, toIndex);
                    tmpMap = marketClient.updateOffLineRegResult(subDataList);
                    // 记录处理结果
                    success += MapUtils.getInteger(tmpMap, "success", 0);
                    Object obj = MapUtils.getObject(tmpMap, "faultList");
                    if (obj != null) {
                        List<String> fList = (List<String>) obj;
                        if (!fList.isEmpty()) {
                            faultList.addAll(fList);
                        }
                    }
                }
                // 更新处理数据
                if (dataList.size() == 0) {
                    // 未解析出数据，处理失败
                    entity.setFaultNum(0);
                    entity.setHandleStatus(2);
                } else if (dataList.size() == success) {
                    // 全部成功
                    entity.setFaultNum(0);
                    entity.setHandleStatus(1);
                } else if (dataList.size() == faultList.size()) {
                    // 全部失败
                    entity.setFaultNum(faultList.size());
                    entity.setHandleStatus(2);
                    entity.setFaultIdList(faultList);
                } else  {
                    // 部分失败
                    entity.setFaultNum(faultList.size());
                    entity.setHandleStatus(3);
                    entity.setFaultIdList(faultList);
                }
                entity.setSuccessNum(success);
                entity.setTimes(entity.getTimes() + 1);
                entity.setLastTime(DateUtil.nowLdt());
                entity.setUpdateTime(DateUtil.nowLdt());
                ysOfflineRegResultService.updateById(entity);
            } catch (Exception e) {
                // 此excel处理失败
                String guid = this.error(e);
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("guid", guid);
                errorMap.put("fileId", entity.getFileId());
                errorMap.put("fileName", entity.getFileName());
                errorList.add(errorMap);
                // 保存处理数据
                entity.setSuccessNum(0);
                entity.setFaultNum(0);
                entity.setTimes(entity.getTimes() + 1);
                entity.setHandleStatus(2);
                entity.setLastTime(DateUtil.nowLdt());
                entity.setUpdateTime(DateUtil.nowLdt());
                ysOfflineRegResultService.updateById(entity);
            }
        }
        String result;
        if (errorList.isEmpty()) {
            // 全部处理，无异常
            result = String.format("Handle ys offline reg result success. Num: %s", entityList.size());
        } else {
            result = String.format("Handle ys offline reg result fault: %s", JsonUtil.toJson(errorList));
        }
        return result;
    }

    @PostConstruct
    private void initXLSReader() throws Exception {
        //构建xml文件输入流
        InputStream inputXML = new BufferedInputStream(this.getClass().getResourceAsStream("/read_ys_6_config.xml"));
        mainReader = ReaderBuilder.buildFromXML(inputXML);
    }

    public static void main(String[] args) {
        List<DataSixUpload> dataList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            dataList.add(new DataSixUpload(
                    String.format("X_USER_CODE_%s", i),
                    String.format("RESULT_%s", i)
            ));
        }
        // 计算处理次数
        int numPerTimes = 12;
        int times = BizUtil.computeHandleTimes(dataList.size(), numPerTimes);
        // 处理数据
        for (int i = 0; i < times; i++) {
            int fromIndex = i * numPerTimes;
            int toIndex = i * numPerTimes + numPerTimes;
            if (toIndex > dataList.size()) {
                toIndex = dataList.size();
            }
            List<DataSixUpload> subDataList = dataList.subList(fromIndex, toIndex);
            System.out.println(String.format("\n=== START %s =================================", i + 1));
            for (int j = 0; j < subDataList.size(); j++) {
                System.out.println(String.format("INDEX=%s, VALUE=%s", j + 1, subDataList.get(j).getUserCode()));
            }
            System.out.println(String.format("=== END %s =================================", i + 1));
        }

    }
}
